<template>
  <div id="components-form-demo-advanced-search">
<!--    搜索区-->
    <a-form class="ant-advanced-search-form" :label-col="{xs: { span: 24 },sm: { span: 5 },}" :form="form" @submit="handleSearch">

      <a-row :gutter="48">
        <a-col :md="8" :sm="24">
          <a-form-item label="关键字">
            <a-input v-model="queryParam.keyword" placeholder="请输入关键字查询"/>
          </a-form-item>
        </a-col>

        <a-col :md="8" :sm="24">
          <a-form-item label="状态">
            <a-select v-model="queryParam.available" placeholder="请选择" default-value="0" style="width: 100px">
              <a-select-option value="0">全部</a-select-option>
              <a-select-option value="1">正常</a-select-option>
              <a-select-option value="2">禁用</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>

        <!--          用户名查询-->
        <a-col :md="8" :sm="24">
          <a-form-item label="用户名">
            <a-input v-model="queryParam.loginName" style="width: 100%" placeholder="请输入用户名"/>
          </a-form-item>
        </a-col>

        <template v-if="isShow">
          <a-col :md="8" :sm="24">
            <a-form-item label="身份证">
              <a-input v-model="queryParam.identity" style="width: 100%" placeholder="请输入身份证"/>
            </a-form-item>
          </a-col>

          <a-col :md="8" :sm="24">
            <a-form-item label="登录时间">
              <a-date-picker v-model="queryParam.lastLoginTime" style="width: 100%" placeholder="请输入登录时间"/>
            </a-form-item>
          </a-col>

          <a-col :md="8" :sm="24">
            <a-form-item label="邮箱地址">
              <a-input v-model="queryParam.email" style="width: 100%" placeholder="请输入邮箱地址"/>
            </a-form-item>
          </a-col>

          <a-col :md="8" :sm="24">
            <a-form-item label="真实姓名">
              <a-input v-model="queryParam.realName" style="width: 100%" placeholder="请输入真实姓名"/>
            </a-form-item>
          </a-col>

          <a-col :md="8" :sm="24">
            <a-form-item label="性别">
              <a-select v-model="queryParam.sex" placeholder="请选择" default-value="0" style="width: 100px">
                <a-select-option value="0">男</a-select-option>
                <a-select-option value="1">女</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :md="8" :sm="24">
            <a-form-item label="地址">
              <a-input v-model="queryParam.address" style="width: 100%" placeholder="请输入地址"/>
            </a-form-item>
          </a-col>

          <a-col :md="8" :sm="24">
            <a-form-item label="手机号">
              <a-input v-model="queryParam.phone" style="width: 100%" placeholder="请输入手机号"/>
            </a-form-item>
          </a-col>

          <a-col :md="8" :sm="24">
            <a-form-item label="身份类型">
              <a-select v-model="queryParam.type" placeholder="请选择" default-value="0" style="width: 100px">
                <a-select-option value="0">全部</a-select-option>
                <a-select-option value="1">超级管理员</a-select-option>
                <a-select-option value="2">管理员</a-select-option>
                <a-select-option value="3">用户</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </template>
      </a-row>

      <a-col offset="16" :md="8" :sm="24">
            <span class="table-page-search-submitButtons" style="float: right">
              <a-button type="primary" html-type="submit">查询</a-button>
              <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
              <a @click="toggle" style="margin-left: 8px">
                {{ isShow ? '收起' : '展开' }}
                <a-icon :type="isShow ? 'up' : 'down'"/>
              </a>
            </span>
      </a-col>
    </a-form>
<!--    数据区-->
    <div class="search-result-list">
      <a-space class="opera">
        <a-button type="primary" icon="plus" @click="handleInsert">新建</a-button>
      </a-space>
<!--      模态框-->
      <a-modal v-model="visible" :title="currentOpera === 1 ? '添加用户':'修改用户'" ok-text="确认" cancel-text="取消" @ok="submitHandler">
<!--        添加-->
        <a-form :form="operaform" v-if="currentOpera === 1">
          <a-form-item
              :label-col="formItemLayout.labelCol"
              :wrapper-col="formItemLayout.wrapperCol"
              label="邮箱名">
            <a-input
                v-decorator="['email',
                { rules: [{ required: true, message: '邮箱为必填项' },
                { type: 'email', message: '邮箱格式有误' },
                { validator: checkEmailHandler }],validateTrigger: ['change', 'blur'] }]"
                placeholder="请输入用户邮箱"/>
          </a-form-item>

          <a-form-item
              :label-col="formItemLayout.labelCol"
              :wrapper-col="formItemLayout.wrapperCol"
              label="身份"
          >
            <a-select placeholder="请选择" style="width: 100px"
                      v-decorator="['type']">
              <a-select-option :value="2">管理员</a-select-option>
              <a-select-option :value="3">用户</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item
              :label-col="formItemLayout.labelCol"
              :wrapper-col="formItemLayout.wrapperCol"
              label="状态"
          >
            <a-select placeholder="请选择" style="width: 100px"
                      v-decorator="['available']">
              <a-select-option :value="1">正常</a-select-option>
              <a-select-option :value="2">禁用</a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
<!--        修改-->
        <a-form :form="operaform" v-else>
          <a-form-item
              v-show="false"
              :label-col="formItemLayout.labelCol"
              :wrapper-col="formItemLayout.wrapperCol"
              label="用户id">
            <a-input
                v-model="userObj.userId"/>
          </a-form-item>


          <a-form-item
              :label-col="formItemLayout.labelCol"
              :wrapper-col="formItemLayout.wrapperCol"
              label="状态"
          >
            <a-select v-if="userObj.userId === 1"
                      disabled
                      placeholder="请选择" style="width: 100px" v-model="userObj.available">
              <a-select-option :value="1">正常</a-select-option>
              <a-select-option :value="0">禁用</a-select-option>
            </a-select>

            <a-select v-else
                      placeholder="请选择" style="width: 100px" v-model="userObj.available">
              <a-select-option :value="1">正常</a-select-option>
              <a-select-option :value="0">禁用</a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </a-modal>

<!--        授权-->
      <a-modal
          :title="'给用户' + currentUser.loginName + '授权'"
          :visible="authVisible"
          :confirm-loading="authConfirmLoading"
          okText="确认"
          okType="primary"
          cancelText="放弃"
          @ok="authHandleOk"
          @cancel="authHandleCancel"
      >
        <a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
          <a-form-item v-if="$store.state.user.loginUser.type === 1" label="角色">
            <a-select
                mode="multiple"
                :value="hasRoleIds"
                style="width: 100%"
                placeholder="请选择角色进行授权"
                @change="handleChange"
            >
              <a-select-option v-for="r in roles" :key="r.roleId">
                {{ r.roleName }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item v-else label="角色">
            <a-select
                mode="multiple"
                :value="hasRoleIds"
                style="width: 100%"
                placeholder="请选择角色进行授权"
                @change="handleChange"
            >
              <a-select-option v-for="r in adminRoles" :key="r.roleId">
                {{ r.roleName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </a-modal>
<!--        授头衔-->
      <a-modal
          :title="'给用户' + currentUser.loginName + '授衔'"
          :visible="rankVisible"
          :confirm-loading="rankConfirmLoading"
          okText="确认"
          okType="primary"
          cancelText="放弃"
          @ok="rankHandleOk"
          @cancel="rankHandleCancel"
      >
        <a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
          <a-form-item v-if="$store.state.user.loginUser.type === 1" label="头衔">
            <a-select
                mode="multiple"
                :value="hasRankIds"
                style="width: 100%"
                placeholder="请选择头衔进行授于"
                @change="rankHandleChange"
            >
              <a-select-option v-for="r in ranks" :key="r.id">
                {{ r.rankName }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item v-else label="角色">
            <a-select
                mode="multiple"
                :value="hasRankIds"
                style="width: 100%"
                placeholder="请选择角色进行授权"
                @change="rankHandleChange"
            >
              <a-select-option v-for="r in adminRanks" :key="r.id">
                {{ r.rankName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </a-modal>

      <a-table :columns="columns"
               :data-source="pageBean.userList"
               :scroll="{ x: 1500}"
               bordered
               :pagination="false"
               :loading="isloading"
               rowKey="userId">

      <span slot="serial" slot-scope="text, record, index">
        {{ index + 1 }}
      </span>

        <span slot="action" slot-scope="text, record">
          <a-space>
            <a-button
                :disabled="
                    record.userId === 1 ||
                    (record.type === 1 && $store.state.user.loginUser.type !== 1) ||
                    record.userId === $store.state.user.loginUser.userId"
                type="primary" @click="authHandler(record)" size="small" icon="lock" title="授权"></a-button>
            <a-button
                :disabled="
                    record.userId === 1 ||
                    (record.type === 1 && $store.state.user.loginUser.type !== 1) ||
                    record.userId === $store.state.user.loginUser.userId"
                type="primary" @click="rankHandler(record)" size="small" icon="idcard" title="授衔"></a-button>
            <a-button
                :disabled="
                    record.userId === 1 ||
                    (record.type === 1 && $store.state.user.loginUser.type !== 1) ||
                    record.userId === $store.state.user.loginUser.userId"
                type="primary" @click="updateUser(record)" size="small" icon="edit" title="编辑"></a-button>
            <a-button :disabled="
                      (record.userId === 1 && $store.state.user.loginUser.userId !== 1) ||
                     (record.type === 1 && $store.state.user.loginUser.type !== 1)"
                      type="danger" @click="resetPwd(record)"
                      size="small"
                      icon="interaction"
                      title="密码重置"></a-button>
            <a-button type="danger"
                      size="small"
                      icon="delete"
                      title="删除"
                      @click="deleteUserHandler(record)"
                      :disabled="record.userId === 1 ||
                      record.userId === $store.state.user.loginUser.userId ||
                      (record.type === 1 && $store.state.user.loginUser.userId !== 1)"></a-button>
          </a-space>
        </span>

        <template slot="footer">
          <a-pagination
              style="text-align: end"
              v-model="pageBean.pageNum"
              :page-size-options="['2', '4', '5']"
              :total="pageBean.total"
              show-size-changer
              :page-size="pageBean.pageSize"
              @showSizeChange="onPageSizeSizeChangeHandler"
              @change="onPageChangeHandler"
          >
            <template slot="buildOptionText" slot-scope="props">
              <span v-if="props.value !== '50'">{{ props.value }}条/页</span>
              <span v-if="props.value === '50'">全部</span>
            </template>
          </a-pagination>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script>
import {
  checkEmailExist,
  getUserList,
  insertUser,
  updateUser,
  resetUserPwd,
  deleteUser,
  getUserHasRoleId,
  saveRoleToUser,
  saveRankToUser,
  getUserHasRankId
} from '@/api/user'
import moment from "moment";
import {DEFAULT_PAGESIZE,DEFAULT_PAGENUM} from "@/constent";
import {getRoleAvalList} from "@/api/role";
import {getRankListPage} from "@/api/sys";

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};
const formTailLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20, offset: 4 },
};
export default {
  name: 'TableList',
  components: {

  },
  data () {
    return {
      // 搜索条件是否展开
      isShow:false,
      // 模态框
      // 添加、修改模态框显示与隐藏
      visible:false,
      currentOpera: 1,
      initQueryParam:{
        pageNum:DEFAULT_PAGENUM,
        pageSize:DEFAULT_PAGESIZE
      },

      // 查询参数
      queryParam:{
        pageNum:DEFAULT_PAGENUM,
        pageSize:DEFAULT_PAGESIZE
      },
      // 分页
      // 表格数据
      userList:[],
      pageBean:{
        total:20,
        pageNum:DEFAULT_PAGENUM,
        pageSize:DEFAULT_PAGESIZE,
        userList:[]
      },
      // 是否加载中
      isloading:true,
      //表头
      columns:[
        {
          title: '编号',
          scopedSlots: { customRender: 'serial' },
          width: 80,
          key: 'index',
          fixed: 'left',
          align:'center',
        },
        {
          title: '用户名',
          width:150,
          dataIndex: 'loginName',
          key: 'loginName',
          align:'center',
          ellipsis: true,
        },
        {
          title: '性别',
          dataIndex: 'sex',
          key: 'sex',
          width: 70,
          align:'center',
          customRender: (text) => text === null ? '' : text === 1 ? '男' : '女'
        },
        {
          title: '用户头像',
          dataIndex: 'avator',
          key: 'avator',
          width: 100,
          align:'center',
          customRender:(text) => <a-avatar src={text} />
        },
        {
          title: '身份',
          key: 'type',
          dataIndex: 'type',
          width: 150,
          align:'center',
          customRender: (text) => text === 1 ? <a-tag color="green">超级管理员</a-tag> : text === 2 ? <a-tag color="blue">管理员</a-tag> : <a-tag color="cyan">用户</a-tag>
        },
        {
          title: '联系方式',
          key: 'phone',
          dataIndex: 'phone',
          align:'center',
          width: 150
        },
        {
          title: '邮箱地址',
          key: 'email',
          dataIndex: 'email',
          width: 200,
          align:'center',
          ellipsis: true,
        },
        {
          title: '状态',
          key: 'available',
          dataIndex: 'available',
          align:'center',
          width: 150,
          customRender:(text) => text === 1 ? <a-tag color="#87d068">正常</a-tag> : <a-tag color="#f50">不可用</a-tag>
        },
        {
          title: '地址',
          key: 'address',
          dataIndex: 'address',
          width: 150,
          align:'center',
          ellipsis: true,
        },
        {
          title: '最后登录时间',
          key: 'lastLoginTime',
          dataIndex: 'lastLoginTime',
          width: 200,
          align:'center',
          ellipsis: true,
          customRender:text => text === null ? '' : moment(text).format("yyyy-MM-DD HH:mm:ss")
        },
        {
          title: '操作',
          key: 'operation',
          fixed: 'right',
          width: 200,
          align:'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      // 展开/收缩 true展开
      expand: false,
      form: this.$form.createForm(this, { name: 'advanced_search' }),
      operaform: this.$form.createForm(this, { name: 'dynamic_rule' }),
      formItemLayout,
      formTailLayout,
      // 用户对象,用于模态框中的修改添加
      userObj:{
        useId:undefined,
        available:undefined,
        email:undefined
      },
      // 授权
      currentUser:{},
      hasRoleIds:[],
      roles:[],
      authVisible: false,
      // 确认加载中
      authConfirmLoading: false,

      // 授衔
      hasRankIds:[],
      ranks:[],
      rankVisible: false,
      // 确认加载中
      rankConfirmLoading: false,
    }
  },
  watch:{
    // 监视参数变化
    queryParam:{
      immediate:true,
      deep:true,
      handler(){
        this.loadUserList();
      }
    }
  },
  mounted() {
    // 获取所有可用角色
    this.loadRolesList();
    // 获取所有头衔信息
    this.loadRanksList();
  },
  computed:{
    adminRoles(){
      const roles = this.roles || [];
      let result = roles.filter(r => r.roleId != 1);
      return result || [];
    },
    adminRanks(){
      const ranks = this.ranks || [];
      let result = ranks.filter(r => r.id != 1);
      return result || [];
    }
  },
  methods:{
    handleChange(value) {
      this.hasRoleIds = value;
    },

    rankHandleChange(value) {
      this.hasRankIds = value;
    },
    // 加载用户数据
    async loadUserList(){
      let result = await getUserList(this.queryParam);
      if(result.code === 200){
        this.isloading = false;
        this.pageBean = result.data;
      }
    },
    // 加载角色信息
    async loadRolesList(){
      const {code,data,msg} = await getRoleAvalList();
      if (code === 200){
        this.roles = data;
      } else {
        this.$message.error(msg);
      }
    },

    // 加载头衔信息
    async loadRanksList(){
      const {code,data,msg} = await getRankListPage(1,100);
      if (code === 200){
        this.ranks = data.data;
      } else {
        this.$message.error(msg);
      }
    },

    /**
     * 每页显示条数改变回调
     * @param current
     * @param pageSize
     */
    onPageSizeSizeChangeHandler(current, pageSize) {
      this.queryParam.pageSize = pageSize;
      this.queryParam.pageNum = DEFAULT_PAGENUM;
    },

    /**
     * 当前页改变回调
     * @param current
     * @param pageSize
     */
    onPageChangeHandler(current){
      this.queryParam.pageNum = current;
    },

    // 新建按钮回调
    handleInsert(){
      this.currentOpera = 1;
      this.visible = true;
    },

    // 检验邮箱是否存在
    checkEmailHandler(rule, value, callback){
      if (value === '' || value === undefined) {
        return callback()
      } else{
        checkEmailExist(value).then(res => {
          const { code,data } = res;
          if (code === 200){
            if (data > 0){
              console.log(data)
              callback(new Error(value + '已存在'))
            }else{
              callback()
            }
          }
        }).catch(() => {
          this.$message.error('请求发送失败');
        })
      }
    },

    // 模态框确认回调
    async submitHandler() {
      const { currentOpera } = this;
      if (currentOpera && currentOpera === 1){
        this.operaform.validateFields(async (err,values) => {
          if (!err) {
            this.visible = false;
            let result = await insertUser(values.email,values.available,values.type);
            if (result.code === 200){
              this.$message.success(result.msg);
            }else{
              this.$message.error(result.msg);
            }
            this.loadUserList();
          }
        });
      }else if(currentOpera && currentOpera === 2){
        const {userId,available} =this.userObj
        let result = await updateUser(userId,available);
        if (result.code === 200){
          this.$message.success(result.msg);
          this.visible = false;
        }else{
          this.$message.error(result.msg);
        }
        this.loadUserList();
      }
    },

    // 重置密码
    resetPwd(record){
      const _this = this;
      this.$confirm({
        title: '确认重置该用户的密码吗?',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          resetUserPwd(record.userId).then(res => {
            if (res.code === 200){
              _this.$message.success(res.msg);
              if (record.userId === _this.$store.state.user.loginUser.userId) {
                _this.$store.dispatch("errorHandler");
              }
            }else{
              _this.$message.error(res.msg);
            }
          }).catch(() => {
            _this.$message.error('发送ajax失败');
          })
        }
      });
    },
    // 修改用户
    updateUser(record){
      // 修改当前为修改状态
      this.currentOpera = 2;
      this.visible = true;
      // 设置表单值
      this.userObj = record;
    },
    // 删除按钮回调
    async deleteUserHandler(record){
      const _this = this;
      this.$confirm({
        title: '删除用户',
        content: '此操作将会删除该用户的所有信息,请谨慎操作?',
        okText: '确认',
        okType: 'danger',
        cancelText: '放弃',
        onOk() {
          deleteUser(record.userId).then(res => {
            const { code,msg } = res;
            if (code === 200){
              _this.$message.success("用户删除成功");
              _this.loadUserList();
            } else {
              _this.$message.error(msg);
            }
          }).catch(error => {
            console.log(error);
            _this.$message.error("操作异常");
          })
        },
        onCancel() {
          console.log("取消了删除");
        },
      });
    },

    // 搜索用户回调
    handleSearch(e) {
      e.preventDefault();
      this.loadUserList(this.queryParam);
    },

    // 重置搜索条件
    handleReset() {
      // 重置搜索条件
      this.queryParam = this.initQueryParam;
      // 重新家在数据
      this.loadUserList();
    },
    // 表单收缩/展开
    toggle() {
      this.isShow = !this.isShow;
    },

    // 授权
    async authHandler(record){
      this.authVisible = true;
      this.currentUser = record;
      // 请求数据
      const {code,data,msg} = await getUserHasRoleId(record.userId);
      if (code === 200){
        this.hasRoleIds = data;
      } else {
        this.$message.error(msg);
      }
    },
    // 确认授权
    async authHandleOk(){
      const userId = this.currentUser.userId;
      const userRoleObj = {
        userId,
        ids: this.hasRoleIds
      };
      this.authConfirmLoading = true;
      const {code,msg} = await saveRoleToUser(userRoleObj);
      if (code === 200){
        this.$message.success(msg);
        this.loadUserList();
      }else {
        this.$message.error(msg);
      }
      setTimeout(() => {
        this.authVisible = false;
        this.authConfirmLoading = false;
        this.currentRole = {};
      }, 1000);
    },

    authHandleCancel(e) {
      console.log('Clicked cancel button');
      this.authVisible = false;
    },

    // 授衔
    async rankHandler(record){
      this.rankVisible = true;
      this.currentUser = record;
      // 请求数据
      const {code,data,msg} = await getUserHasRankId(record.userId);
      if (code === 200){
        this.hasRankIds = data;
      } else {
        this.$message.error(msg);
      }
    },
    // 确认授权
    async rankHandleOk(){
      const userId = this.currentUser.userId;
      const userRankObj = {
        userId,
        ids: this.hasRankIds
      };
      this.rankConfirmLoading = true;
      const {code,msg} = await saveRankToUser(userRankObj);
      if (code === 200){
        this.$message.success(msg);
        this.loadUserList();
      }else {
        this.$message.error(msg);
      }
      setTimeout(() => {
        this.rankVisible = false;
        this.rankConfirmLoading = false;
        this.currentRank = {};
      }, 1000);
    },

    rankHandleCancel(e) {
      console.log('Clicked cancel button');
      this.rankVisible = false;
    },
  }
}
</script>

<style scoped>
.ant-advanced-search-form {
  padding: 24px;
  background: #fbfbfb;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  overflow: hidden;
}

.ant-advanced-search-form .ant-form-item {
  display: flex;
}

.ant-advanced-search-form .ant-form-item-control-wrapper {
  flex: 1;
  width: 100px;
}
#components-form-demo-advanced-search .search-result-list {
  margin-top: 16px;
  border: 1px dashed #e9e9e9;
  border-radius: 6px;
  background-color: #fafafa;
  min-height: 200px;
  padding-top: 20px;
}
.opera{
  margin-bottom: 10px;
  margin-left: 10px;
}
</style>
